<template>
  <div class="knowledge-points-container">
    <el-card class="knowledge-points-card">
      <template #header>
        <div class="card-header">
          <span>知识点管理</span>
          <el-button type="primary" @click="handleAdd">添加知识点</el-button>
        </div>
      </template>

      <!-- 分类选择 -->
      <div class="filter-container">
        <el-select
          v-model="selectedCategory"
          placeholder="选择课程分类"
          @change="handleCategoryChange"
          clearable
        >
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </el-select>
      </div>

      <!-- 知识点列表 -->
      <el-table :data="knowledgePoints" style="width: 100%">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="知识点名称" prop="name" />
        <el-table-column label="所属分类" prop="categoryName" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加知识点' : '编辑知识点'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="知识点名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入知识点名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择所属分类"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入知识点描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  addKnowledgePoint,
  getKnowledgePoints,
  getKnowledgePointsByCategory,
  updateKnowledgePoint,
  deleteKnowledgePoint
} from '@/api/knowledgePoint'
import { lessonCategoryListService } from '@/api/lesson'

const knowledgePoints = ref([])
const categories = ref([])
const selectedCategory = ref(null)
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentPoint = ref(null)

const form = ref({
  name: '',
  categoryId: null,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入知识点名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ]
}

const formRef = ref(null)

// 获取课程分类列表
const fetchCategories = async () => {
  try {
    const res = await lessonCategoryListService()
    if (res.code === 0) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('获取课程分类失败:', error)
    ElMessage.error('获取课程分类失败')
  }
}

// 获取知识点列表
const fetchKnowledgePoints = async () => {
  try {
    const res = await getKnowledgePoints()
    if (res.code === 0) {
      knowledgePoints.value = res.data
    }
  } catch (error) {
    console.error('获取知识点列表失败:', error)
    ElMessage.error('获取知识点列表失败')
  }
}

// 处理分类变化
const handleCategoryChange = async (categoryId) => {
  try {
    if (categoryId) {
      const res = await getKnowledgePointsByCategory(categoryId)
      if (res.code === 0) {
        knowledgePoints.value = res.data
      }
    } else {
      await fetchKnowledgePoints()
    }
  } catch (error) {
    console.error('获取分类知识点失败:', error)
    ElMessage.error('获取分类知识点失败')
  }
}

// 添加知识点
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    categoryId: null,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑知识点
const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentPoint.value = row
  form.value = {
    name: row.name,
    categoryId: row.categoryId,
    description: row.description
  }
  dialogVisible.value = true
}

// 删除知识点
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个知识点吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteKnowledgePoint(row.id)
    ElMessage.success('删除成功')
    if (selectedCategory.value) {
      await handleCategoryChange(selectedCategory.value)
    } else {
      await fetchKnowledgePoints()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除知识点失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await addKnowledgePoint(form.value)
      ElMessage.success('添加成功')
    } else {
      await updateKnowledgePoint(currentPoint.value.id, form.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    if (selectedCategory.value) {
      await handleCategoryChange(selectedCategory.value)
    } else {
      await fetchKnowledgePoints()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(async () => {
  await fetchCategories()
  await fetchKnowledgePoints()
})
</script>

<style scoped>
.knowledge-points-container {
  padding: 20px;
}

.knowledge-points-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style> 